<template>
  <div class="poster-page">
    <MEditor v-model:title="formState.title" v-model="formState.content" @event="handleEvent"/>
    <a-drawer
        v-model:visible="visible"
        class="custom-class"
        title="文章编辑"
        placement="right"
        width="500px"
    >
      <a-form
          ref="formRef"
          :model="formState"
          :rules="formRules"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
          @finish="onFinish"
          @finishFailed="onFinishFailed"
      >
        <a-form-item label="文章标题" name="title">
          <a-input v-model:value="formState.title" showCount allowClear/>
        </a-form-item>
        <a-form-item label="文章简介" name="summary">
          <a-textarea
              v-model:value="formState.summary"
              showCount
              allowClear
              auto-size
              :rows="4"
          />
        </a-form-item>
        <a-form-item label="文章封面" name="cover" required>
          <CropperUpload v-model:file="formState.cover"/>
        </a-form-item>
        <a-form-item label="文章分类" name="category_id">
          <a-select
              v-model:value="formState.category_id"
              :options="cateList"
              showSearch
              :showArrow="false"
              :filter-option="false"
              @search="searchCate"
          >
            <template #dropdownRender="{ menuNode: menu }">
              <VNodes :vnodes="menu"/>
              <a-divider style="margin: 4px 0"/>
              <div
                  style="padding: 4px 8px; cursor: pointer"
                  @mousedown="(e) => e.preventDefault()"
                  @click="addCateItem"
              >
                <plus-outlined/>
                添加分类
              </div>
            </template>
          </a-select>
        </a-form-item>

        <a-form-item label="文章标签" name="tag_id">
          <a-select
              v-model:value="formState.tag_id"
              mode="multiple"
              :options="tagList"
              showSearch
              :showArrow="false"
              :filter-option="false"
              @search="searchTag"
          >
            <template #dropdownRender="{ menuNode: menu }">
              <VNodes :vnodes="menu"/>
              <a-divider style="margin: 4px 0"/>
              <div
                  style="padding: 4px 8px; cursor: pointer"
                  @mousedown="(e) => e.preventDefault()"
                  @click="addTagItem"
              >
                <plus-outlined/>
                添加标签
              </div>
            </template>
          </a-select>
        </a-form-item>

        <a-form-item label="文章状态" name="status">
          <a-radio-group v-model:value="formState.status">
            <a-radio-button value="0">草稿</a-radio-button>
            <a-radio-button value="1">发布</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="置顶状态" name="is_top">
          <a-radio-group v-model:value="formState.is_top">
            <a-radio-button value="0">不置顶</a-radio-button>
            <a-radio-button value="1">置顶</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="推荐状态" name="is_nice">
          <a-radio-group v-model:value="formState.is_nice">
            <a-radio-button value="0">普通</a-radio-button>
            <a-radio-button value="1">精品</a-radio-button>
          </a-radio-group>
        </a-form-item>

        <a-form-item label="开启评论" name="allow_comment">
          <a-radio-group v-model:value="formState.allow_comment">
            <a-radio-button value="0">不开启</a-radio-button>
            <a-radio-button value="1">开启</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 0, span: 24 }">
          <a-space align="end" style="float:right">
            <a-button @click="onSave">保存</a-button>
            <a-button type="primary" html-type="submit">提交</a-button>
          </a-space>
        </a-form-item>
      </a-form>
      <TagModal ref="tagDrawerRef" title="添加标签"/>
    </a-drawer>

    <div class="fixed-options">
      <appstore-add-outlined @click="visible = !visible" style="font-size: 40px;color: #fff"/>
    </div>
  </div>
</template>

<script>

import { ref, createVNode, computed, onMounted } from "vue";
import { message, Modal } from "ant-design-vue";
import { useRoute, useRouter } from "vue-router";

import MEditor from '@/components/MEditor'
import TagModal from "@/components/TagModel"
import CropperUpload from '@/components/CropperUpload'

import { detail, insert, update } from "@/api/article";
import { CODEENUM } from "@/config";
import store from "@/store";

export default {
  components: {
    MEditor, TagModal, CropperUpload,
    VNodes: (_, { attrs }) => {
      return attrs.vnodes
    },
  },
  setup() {
    const { query } = useRoute()
    const articleId = ref(query.id)

    const router = useRouter()

    const visible = ref(false);

    const formRef = ref(null);

    const tagDrawerRef = ref(null)
    const formState = ref({
      id: "",
      title: "",
      cover: "/202304/865c166e62cd45942c9fc6403.jpg",
      summary: "",
      status: "0",
      content: "",
      tag_id: [],
      category_id: "",
      allow_comment: "0",
      is_top: "0",
      is_nice: "0",
    })
    const formRules = {
      title: [{ required: true, message: "请输入文章标题！" }],
      summary: [{ required: true, message: "请输入文章简介！" }],
      category_id: [{ required: true, message: "请选择文章分类！" }],
      tag_id: [{ required: true, message: "请选择文章标签！" }],
      status: [{ required: true, message: "请选择文章状态！" }],
      is_top: [{ required: true, message: "请选择置顶状态！" }],
      is_nice: [{ required: true, message: "请选择推荐状态！" }],
      allow_comment: [{ required: true, message: "请选择开启评论状态！" }],
      content: [{ required: true, message: "请输入文章内容！" }],
    }
    const getArticleDetail = async (id) => {
      const { data, code } = await detail({ id })
      if (code !== CODEENUM.GD_SUCCESS) return
      formState.value = data
      formState.value.tag_id = data.tag_id?.split(',') || []
    }

    const cateList = computed(() =>
        store.getters.cateList.map((e) => {
          return { label: e.name, value: e.id }
        })
    )
    const tagList = computed(() =>
        store.getters.tagList.map((e) => {
          return { label: e.name, value: e.id }
        })
    )

    const onSave = async () => {
      const params = JSON.parse(JSON.stringify(formState.value))
      params.tag_id = params.tag_id?.join(',') || ''
      params.content = params.content?.toString() || ''
      delete params.tags
      const { code } = params.id ? await update(params) : await insert(params)
      if (code !== CODEENUM.OP_SUCCESS) return
    }

    const onFinish = async () => {
      await onSave()
      router.push({ path: `/article`, query: { id: formState.value.id } })
    }

    // 表单校验失败
    const onFinishFailed = async () => {
      message.warning("请检查表单必填项！")
    }
    const searchTag = (val) => {
      console.log(val)
    }
    const searchCate = (val) => {
      console.log(val)
    }

    const addCateItem = () => {
      console.log("添加分类")
    }

    const addTagItem = () => {
      tagDrawerRef.value.showDrawer()
      console.log("添加标签")
    }


    const handleEvent = async ({ type, value, back }) => {
      switch (type) {
        case 'back':
          showConfirm({
            content: '确定要返回吗，文章未保存部分将会丢失！',
            ok: () => {
              router.go(-1);
            }
          });
          break;
        case 'save':
          await onSave(formState.value)
          if (back == 1) {
            showConfirm({
              content: '文章已保存，需要返回吗！',
              okText: '返回',
              ok: () => {
                router.go(-1);
              }
            });
          }
          break;
        case 'submit':
          if (!formRef.value) {
            return message.warn("请先检查文章各字段是否填写完成！")
          }
          formRef.value.validate().then(() => {
            showConfirm({
              content: '确定要发布该文章吗！',
              ok: () => {
                onSave(formState.value)
              }
            });
          }).catch(() => {
            return message.warn("请先检查文章各字段是否填写完成！")
          })
          break;
      }
    }
    const showConfirm = ({ title = '提示', content, ok, cancel, okText = '确定', cancelText = '取消' }) => {
      Modal.confirm({
        title,
        content: createVNode('div', null, content),
        okText,
        cancelText,
        onOk() {
          ok && ok();
        },
        onCancel() {
          cancel && cancel()
        },
        class: 'test',
      });
    };

    onMounted(() => {
      if (articleId.value) {
        getArticleDetail(articleId.value)
      }
    })


    return {
      formRef,
      handleEvent,

      visible,
      cateList,
      tagList,
      formState,
      formRules,
      onSave,
      onFinish,
      onFinishFailed,

      searchTag,
      searchCate,
      addCateItem,
      addTagItem,

      tagDrawerRef,
    };
  }
}
</script>

<style lang="less" scoped>

.poster-page {
  position: relative;
  min-height: 100vh;
  min-width: 100vw;
}

.fixed-options {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  right: 0;
  bottom: 30%;
  width: 80px;
  height: 80px;
  background: #4dd2ff;
  border-radius: 20px 0 0 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
